﻿namespace Vboot.Core.Module.Sys;

[ApiDescriptionSettings("Sys", Tag = "接口管理-接口")]
public class SysApiMainApi : IDynamicApiController
{
    private readonly SqlSugarRepository<SysApiMain> _repo;
    
    public SysApiMainApi(
        SqlSugarRepository<SysApiMain> repo)
    {
        _repo = repo;
    }

    
    [QueryParameters]
    public async Task<dynamic> GetTree()
    {
        var treeList = await _repo.Context
            .SqlQueryable<SysApiMain>(
                "select id,pid,id as name,type from sys_api_main where avtag=1")
            .ToTreeAsync(it => it.children, it => it.pid, null);
        return treeList;
    }
    
    [QueryParameters]
    public async Task<dynamic> GetTreer()
    {
        var treeList = await _repo.Context
            .SqlQueryable<SysApiMain>(
                "select id,pid,id as name,type from sys_api_main where avtag=1 and type is null")
            .ToTreeAsync(it => it.children, it => it.pid, null);
        return treeList;
    }
    
    
    public async Task<dynamic> GetList()
    {
        return await _repo.GetListAsync();
    }
    
    [QueryParameters]
    public async Task<dynamic> Get(string id,string pid)
    {
        var pp = XreqUtil.GetPp();
        var items = await _repo.Context.Queryable<SysApiMain>()
            .WhereIF(!string.IsNullOrWhiteSpace(id), t => t.id.Contains(id.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(pid), t => t.pid==pid)
            .Where(t=>t.type!=null)
            .Select((t) => new {t.id, t.url,t.type,t.crtim,t.uptim})
            .ToPageListAsync(pp.page, pp.pageSize, pp.total);
        return RestPageResult.Build(pp.total.Value, items);
    }
    
    public async Task<SysApiMain> GetOne(string id)
    {
        var main = await _repo.Context.Queryable<SysApiMain>()
            .Where(it => it.id == id).FirstAsync();
        return main;
    }

    public async Task<string> Post(SysApiMain main)
    {
        main.id = YitIdHelper.NextId() + "";
        await _repo.InsertAsync(main);
        return main.id;
    }

    public async Task<string> Put(SysApiMain main)
    {
        main.uptim = new DateTime();
        await _repo.UpdateAsync(main);
        return main.id;
    }

    public async Task Delete(string ids)
    {
        var idArr = ids.Split(",");
        await _repo.Context.Deleteable<SysApiMain>().In(idArr).ExecuteCommandAsync();
    }
    
}